package com.aoip.telemetry.telemetry.configureui.business.commonconfig.mergeruledetail.service.impl;

import com.aoip.telemetry.telemetry.configureui.business.commonconfig.mergeruledetail.mapper.MergeRuleDetailMapper;
import com.aoip.telemetry.telemetry.configureui.business.commonconfig.mergeruledetail.service.MergeRuleDetailService;
import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import com.aoip.telemetry.telemetry.entity.merge.DataMergeRuleDetailEntity;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author chenbai
 * @version 1.0
 * @date 2022/10/17 22:30
 */
@Service
@DS("telemetry")
public class MergeRuleDetailServiceImpl implements MergeRuleDetailService {
    @Resource
    private MergeRuleDetailMapper mapper;
    @Resource
    private RedisCache redisCache;

    @Override
    public List<DataMergeRuleDetailEntity> list(DataMergeRuleDetailEntity entity) {
        QueryWrapper<DataMergeRuleDetailEntity> queryWrapper = new QueryWrapper<>();
//        String ruleGroupName = entity.getRuleSourceTable();
//        if (StringUtils.hasText(ruleGroupName)) {
//            queryWrapper.like(true, "rule_group_name", ruleGroupName);
//        }
//        String ruleGroupTargetTable = entity.getRuleGroupTargetTable();
//        if (StringUtils.hasText(ruleGroupTargetTable)) {
//            queryWrapper.eq(true, "rule_group_target_table", ruleGroupTargetTable);
//        }
        return mapper.selectList(queryWrapper);
    }

    @Override
    public DataMergeRuleDetailEntity detail(String id) {
        return mapper.selectById(id);
    }

    @Override
    public int insert(DataMergeRuleDetailEntity entity) {
        return mapper.insert(entity);
    }

    @Override
    public int update(DataMergeRuleDetailEntity entity) {
        return mapper.updateById(entity);
    }

    @Override
    public int initCache() {
        List<DataMergeRuleDetailEntity> list = list(new DataMergeRuleDetailEntity());
        Collection<String> keys = redisCache.keys(CacheKeyEnum.DATA_MERGE_RULE_DETAIL + ":*");
        redisCache.deleteObject(keys);
        for (DataMergeRuleDetailEntity detailEntity : list) {
            String ruleGroupId = detailEntity.getRuleGroupId();
            redisCache.setCacheList(CacheKeyEnum.DATA_MERGE_RULE_DETAIL + ":" + ruleGroupId, detailEntity);
        }
        return list.size();
    }

    @Override
    public void delete(Long[] ids) {
        mapper.deleteBatchIds(Arrays.asList(ids));
    }
}
